package com.jackstraw.jack_base.datasource.database.parten.entity.bean;

import com.jackstraw.jack_base.datasource.common.entity.AbstractPropertiesEntity;
import com.jackstraw.jack_base.datasource.database.parten.entity.DataBaseEntity;
import com.jackstraw.jack_base.datasource.database.parten.entity.enums.DataBaseSchemaTypeEnum;
import com.jackstraw.jack_base.datasource.database.parten.exception.BadDataBaseException;
import com.jackstraw.jack_base.util.CollectionUtil;
import com.jackstraw.jack_base.util.ObjectUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 数据库单数据源配置文件实体
 */
@Data
@Slf4j
public class DataBasePropertiesEntity<DBE extends DataBaseEntity<DBE>>
        extends AbstractPropertiesEntity<DataBasePropertiesEntity<DBE>> {

    /**
     * 数据源类型
     */
    private DataBaseSchemaTypeEnum dataBaseSchemaTypeEnum = DataBaseSchemaTypeEnum.none;


    /**
     * 默认配置
     */
    private DBE dataBaseEntity;

    /**
     * 当前数据源读配置
     * <p>
     * 若数据源类型为none时，此项为空
     */
    private List<DBE> readDataBaseEntityList;

    @Override
    public void resolve(String tenantName, String dataSourceName) {

        if (ObjectUtil.ObjectUtilByLang3.isEmpty(this.dataBaseSchemaTypeEnum)) {
            throw new BadDataBaseException("001", "租户[{}]下数据源名称为[{}]的数据源类型为空", tenantName, dataSourceName);
        }

        //校验主数据源
        if (ObjectUtil.ObjectUtilByLang3.isEmpty(this.dataBaseEntity)) {
            throw new BadDataBaseException("002", "租户[{}]下数据源名称为[{}]的数据源默认配置为空", tenantName, dataSourceName);
        }

        if (DataBaseSchemaTypeEnum.rw.equals(dataBaseSchemaTypeEnum)) {
            //说明是读写数据源
            if (CollectionUtil.isEmpty(this.readDataBaseEntityList)) {
                log.warn("租户[{}]下数据源名称为[{}]的数据源类型为读写数据源，但是读数据源为空", tenantName, dataSourceName);
                return;
            }
            this.readDataBaseEntityList.stream().forEach(dataBaseEntity -> {
                //校验主数据源
                if (ObjectUtil.ObjectUtilByLang3.isEmpty(dataBaseEntity)) {
                    throw new BadDataBaseException("003", "租户[{}]下数据源名称为[{}]的读数据源中存在空配置", tenantName, dataSourceName);
                }
            });
        }

    }
}

